package cn.dakaqi.utils.zip;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Enumeration;

public class ParseZip
{

    public static void main(String[] args)
    {

        try
        {
            ParseZip.unZip(new File("D:/testrar/something.zip"), "D:/testrar/");
        } catch (Exception e)
        {
            e.printStackTrace();

        }
    }

    public static String unZip(File zip, String root) throws Exception
    {
        String index = "";
        try
        {
            ZipFile zipFile = new ZipFile(zip, "gbk");
            Enumeration e = zipFile.getEntries();
            byte ch[] = new byte[256];
            while (e.hasMoreElements())
            {
                ZipArchiveEntry zipEntry = (ZipArchiveEntry) e.nextElement();
                String temp = zipEntry.getName();
                if ("html".equals(temp.substring(temp.lastIndexOf('.') + 1)))
                {
                    index = temp;
                }
                File zfile = new File(root + temp);
                File fpath = new File(zfile.getParentFile().getPath());

                if (zipEntry.isDirectory())
                {
                    if (!zfile.exists())
                        zfile.mkdirs();
                } else
                {
                    if (!fpath.exists())
                        fpath.mkdirs();
                    FileOutputStream fouts = new FileOutputStream(zfile);
                    InputStream in = zipFile.getInputStream(zipEntry);
                    int i;
                    while ((i = in.read(ch)) != -1)
                        fouts.write(ch, 0, i);
                    fouts.close();
                    in.close();
                }
            }

        } catch (Exception e)
        {
            System.err.println("Exception from ZipUtil -> unZip() : "
                    + e.getMessage());
            e.printStackTrace(System.err);
            throw e;
        } finally
        {
            return index;
        }
    }


}
